package lhy.frontend;

import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import lhy.AppStart;
import lhy.orm.annotation.SimpleMapping;
import lhy.utils.ReflectUtils;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class FrontendUtils {
	public static String getMethodDescription(String method){
		return switch (method){
			case "POST"->"添加";
			case "PUT"->"修改";
			case "DELETE"->"删除";
			default ->"";
		};
	}

	//把jsp传进来的请求转换成对象
    public static <T extends Serializable> T getFormObject( HttpServletRequest qu,Class<T> entityClass){
        T instance = ReflectUtils.newInstance(entityClass);
        for (Field field : ReflectUtils.getAccessibleFields(entityClass)) {
            String fieldVal = qu.getParameter(field.getName());
            ReflectUtils.setFieldValue(field,instance,fieldVal);
        }
        return instance;
    }
	//从ajax传进来的payload，解析成参数map
	public static Map<String,Object> getParamMapFromAjax(ServletRequest qu){
		Map<String,Object> paramMap = new HashMap<>();
		String payload = null;
		try {
			payload = IOUtils.toString(qu.getReader());
		} catch (IOException e) {
			e.printStackTrace();
		}
		payload= URLDecoder.decode(payload, StandardCharsets.UTF_8);
		String[] params = payload.split("&");
		for (String fieldAndVal : params) {
			String fieldName = null;
			Object fieldVal = null;
			try {
				fieldName = fieldAndVal.split("=")[0];
				fieldVal = fieldAndVal.split("=")[1];
			} catch (ArrayIndexOutOfBoundsException e) {
				AppStart.LOGGER.warn("警告：{} 值为空",fieldName);
				fieldVal="";
			}
			paramMap.put(fieldName,fieldVal);
		}
		return paramMap;
	}
	public static <T> T getFormAjaxObject(Map<String, Object> map,Class<T> entityClass){
		T instance = ReflectUtils.newInstance(entityClass);
		map.forEach((name,val)->{
			Field field =ReflectUtils.getFieldByName(entityClass,name);
			ReflectUtils.setFieldValue(field,instance,val);
		});
		return instance;
	}
    public static <T > T getFormAjaxObject( HttpServletRequest qu,Class<T> entityClass){
        return getFormAjaxObject(getParamMapFromAjax(qu),entityClass);
    }
    public static List<Object> getTableFieldValues(Object instance,Class<? extends Serializable > entityClass){
    	return Arrays.stream(ReflectUtils.getAccessibleFields(entityClass))
                .map(field -> FrontendUtils.getFieldValue(field, instance))
              
                .collect(Collectors.toList());
    	
    	
    }
    public static Object getFieldValue(Field field,Object instance) {
    	SimpleMapping simpleMapping = field.getAnnotation(SimpleMapping.class);
    	Object fieldValue = ReflectUtils.getFieldValue(field, instance);
    	if(simpleMapping!=null) {
    		for(String mapping: simpleMapping.value().split(",")) {
    			String[] split = mapping.split("=");
    			if(fieldValue.equals(split[0])) {
    				return split[1];
    			}
    		}
    	}
    	return fieldValue;
    }
}
